package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.User;
import com.weilai.service.CaptchaService;
import com.weilai.service.EmailService;
import com.weilai.service.UserService;
import com.weilai.service.serviceImpl.EmailServiceImpl;
import com.weilai.service.serviceImpl.UserServiceImpl;
import com.weilai.util.PasswordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;

@Api(tags = "忘记密码", description = "提供忘记密码方法的接口")
@Controller
public class ResetPasswordController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    @ApiOperation(value = "忘记密码方法", notes = "忘记密码方法，需要输入用户邮箱、验证码、新密码")
    @ApiResponses({
            @ApiResponse(code = 200, message = "重置成功")
    })
    //重置密码
    @PostMapping("/forgetPassword")
    public ModelAndView register(@RequestParam String email,
                                 @RequestParam String code,
                                 @RequestParam String password,
                                 HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("forgetPasswordEmail", "");
        session.setAttribute("forgetPasswordPassword", "");
        session.setAttribute("forgetPasswordCode", "");

        try {

            ModelAndView mav = new ModelAndView();
            User user = userService.getUserByEmail(email);

            // 检查用户是否存在
            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "没有该账户，请先注册");
            }

            // 验证码校验
            if (captchaService.getByEamil(email)==null || !code.equals(String.valueOf(captchaService.getByEamil(email).getCaptchaCode()))) {
                session.setAttribute("forgetPasswordEmail", email);
                session.setAttribute("forgetPasswordPassword", password);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "验证码错误，请重试");
            }

            // 密码复杂度校验
            if (password.length() < 6 || password.length() > 20) {
                session.setAttribute("forgetPasswordEmail", email);
                session.setAttribute("forgetPasswordCode", code);
                session.setAttribute("forgetPasswordPassword", password);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "密码长度需在6-20位之间");
            }

            boolean hasLetter = password.chars().anyMatch(Character::isLetter);
            if (!hasLetter) {
                session.setAttribute("forgetPasswordEmail", email);
                session.setAttribute("forgetPasswordCode", code);
                session.setAttribute("forgetPasswordPassword", password);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "密码必须包含字母");
            }

            // 更新密码
//            user.setPassword(PasswordUtil.encode(password));
            user.setPassword(password);
            try {
                userService.updateUser(user);
            } catch (Exception e) {
                session.setAttribute("forgetPasswordEmail", email);
                session.setAttribute("forgetPasswordCode", code);
                session.setAttribute("forgetPasswordPassword", password);
                throw new SystemException(Code.SYSTEM_DB_ERROR, "密码更新失败，请稍后重试", e);
            }

            mav.setViewName("redirect:/login");

            session.removeAttribute("forgetPasswordEmail");
            session.removeAttribute("forgetPasswordPassword");
            session.removeAttribute("forgetPasswordCode");

            return mav;
        } catch (BusinessException e) {
            session.setAttribute("forgetPasswordEmail", email);
            session.setAttribute("forgetPasswordCode", code);
            session.setAttribute("forgetPasswordPassword", password);
            throw e; // 业务异常直接抛出
        } catch (Exception e) {
            session.setAttribute("forgetPasswordEmail", email);
            session.setAttribute("forgetPasswordCode", code);
            session.setAttribute("forgetPasswordPassword", password);
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "重置密码过程中出现系统错误", e);
        }
    }

    @ApiOperation(value = "发送验证码方法", notes = "发送验证码，需要输入用户邮箱")
    @ApiResponses({
            @ApiResponse(code = 200, message = "发送成功")
    })
    //发送验证码
    @PostMapping("/forgetPassword/sendCode")
    public ModelAndView sendCode(@RequestParam String email, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("forgetPasswordEmail", "");

        try {
            ModelAndView mav = new ModelAndView();

            // 检查用户是否存在
            User user = userService.getUserByEmail(email);
            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "该邮箱未注册，请先注册");
            }

            //发送验证码
            captchaService.sendCode(email);

            mav.addObject("result", "验证码已发送至您的邮箱");
            mav.setViewName("forgetPassword");
            session.removeAttribute("forgetPasswordEmail");

            return mav;
        } catch (BusinessException e) {
            session.setAttribute("forgetPasswordEmail", email);
            throw e;
        } catch (Exception e) {
            session.setAttribute("forgetPasswordEmail", email);
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "发送验证码过程中出现系统错误", e);
        }
    }
}
